<template>
  <el-dialog title="选择商品" :visible.sync="dialogVisible" :close-on-click-modal="false">
    <div class="content" @click.stop="()=>{}">
      <SearchForm :listQuery='listQuery' :queryConfig="queryConfig" :labelWidth="100" :search="search" />
      <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border @row-click="clickRow">
        <el-table-column align="center" width="50">
          <template slot-scope="scope">
            <label class="input-radio" v-if="config.count === 1">
              <input type="radio" :value="{goodsId: scope.row.goodsId}" v-model="itemsRadio" @change="(e) => setValue(e.target.checked, scope.row)" />
              <span></span>
            </label>
            <label class="input-checkbox" v-else>
              <input type="checkbox" :value="{goodsId: scope.row.goodsId}" v-model="itemsCheck"
                @change="(e) => setValue(e.target.checked, scope.row)" />
              <span></span>
            </label>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商品款号" prop="serialNo" width="110"></el-table-column>
        <el-table-column align="center" label="商品名称" prop="name" min-width="110" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column align="center" label="虚拟商品" width="100" v-if="!config.goodsType">
            <template slot-scope="scope">
              <span v-if="scope.row.goodsType===2" style="color: red">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column> -->
        <el-table-column align="center" label="商品分类" prop="backCatName" min-width="60"></el-table-column>
        <el-table-column align="center" label="商品状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.upshelf===1">已上架</span>
            <span v-else style="color: #bbb">已下架</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否售卖" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.isSell===1">是</span>
            <span v-else style="color: #bbb">否</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page.sync="listQuery.pageIndex" :page-size="listQuery.pageSize" background
        layout="total, prev, pager, next, jumper" style="text-align: center" :total="listTotal">
      </el-pagination>
    </div>
    <div slot="footer" class="dialog-footer" @click.stop="()=>{}">
      <el-button type="primary" :loading="btnLoading" @click="choose">确定</el-button>
      <el-button @click="close">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getMerchantWarehouse } from '../../api/common'
import { getGoodsList, getFrontCatTree } from '../../api/goodMiddleStage'
import SearchForm from '@/components/searchForm'
export default {
  name: 'choose-goods',
  components: {
    SearchForm
  },
  props: {
    config: {
      type: Object,
      default() {
        return {}
      }
    },
    selected: {
      type: Array,
      default() {
        return []
      }
    }
  },

  data() {
    return {
      dialogVisible: true,
      btnLoading: false,
      categoryLoading: true,
      result: this.selected,
      itemsCheck: this.selected.length
        ? this.selected.map(item => {
            return { goodsId: item.goodsId }
          })
        : [],
      itemsRadio: this.selected.length
        ? { goodsId: this.selected[0].goodsId }
        : {},
      listQuery: {
        frontCatIds: [],
        frontCatId: '',
        serialNo: '',
        name: '',
        onSale: '',
        businessModel: '',
        merchantId: '',
        excludeCrush: this.config.excludeCrush || 0,
        pageIndex: 1,
        pageSize: 8,
        queryType: 3
      },
      queryConfig: [
        {
          prop: 'frontCatIds',
          type: 'cascader',
          label: '商品分类',
          showAll: false, // 级联选择 是否展示全部
          settings: { value: 'id', label: 'name' },
          data: []
        },
        {
          prop: 'serialNo',
          type: 'input',
          label: '商品款号'
        },
        {
          prop: 'name',
          type: 'input',
          label: '商品名称'
        },
        {
          prop: 'onSale',
          type: 'select',
          label: '是否售卖',
          data: [
            {
              label: '全部',
              value: ''
            },
            {
              label: '是',
              value: 1
            },
            {
              label: '否',
              value: 0
            }
          ]
        },
        {
          prop: 'businessModel',
          type: 'select',
          label: '渠道类型',
          data: [
            {
              label: '直营',
              value: 1
            },
            {
              label: '招商',
              value: 2
            }
          ]
        },
        {
          prop: 'merchantId',
          type: 'select',
          label: '供应商',
          data: []
        }
      ],

      list: [],
      listTotal: 0,
      listLoading: false
    }
  },
  created() {
    this.getFrontTree()
    this.getList()
    this.getMerchantWarehouseList()
  },
  methods: {
    // 获取列表
    async getList() {
      this.listLoading = true
      try {
        const { data } = await getGoodsList(this.listQuery)
        this.list = data.data
        this.listTotal = data.total
        this.listLoading = false
      } catch (error) {
        console.log(error)
        this.list = []
        this.listTotal = 0
        this.listLoading = false
      }
    },
    // 前台类树
    async getFrontTree() {
      try {
        const { data } = await getFrontCatTree()
        this.queryConfig[0].data = data.treeList
        this.generateCatTree(this.queryConfig[0].data)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取供应商、仓库列表
    getMerchantWarehouseList() {
      getMerchantWarehouse().then(({ data }) => {
        this.queryConfig[5].data = data.viewList
          .filter(item => item.supplyCode !== null)
          .map(it => {
            return {
              label: it.supplyName,
              value: it.supplyCode
            }
          })

        console.log('供应商', this.merchants)
      })
    },
    // 生成类目数 删除children为空的选项
    generateCatTree(val) {
      val.forEach(it => {
        if (it.children.length > 0) {
          this.generateCatTree(it.children)
        } else {
          delete it.children
        }
      })
    },
    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields()
      })
    },
    // 搜索
    search() {
      if (this.listQuery.frontCatIds) {
        this.listQuery.frontCatId = this.listQuery.frontCatIds.slice(-1)[0]
      } else {
        this.listQuery.frontCatId = ''
      }
      this.listQuery.pageIndex = 1
      this.getList()
    },
    // 切换分页
    handleCurrentChange(page) {
      this.listQuery.pageIndex = page
      this.getList()
    },
    // 选择change
    setValue(checked, row) {
      if (checked) {
        if (this.config.count === 1) {
          this.result = [row]
        } else {
          this.result.push({ ...row })
        }
      } else {
        let index = this.itemsCheck.findIndex(
          item => row.goodsId === item.goodsId
        )
        this.result.splice(index, 1)
      }
    },
    // 单击行
    clickRow(row) {
      if (this.config.count === 1) {
        this.itemsRadio = { goodsId: row.goodsId }
        this.result = [row]
      } else {
        let index = this.itemsCheck.findIndex(
          item => row.goodsId === item.goodsId
        )
        if (index < 0) {
          this.itemsCheck.push({ goodsId: row.goodsId })
          this.result.push({ ...row })
        } else {
          this.itemsCheck.splice(index, 1)
          this.result.splice(index, 1)
        }
      }
    },
    // 通过tag删除
    delItem(index) {
      this.itemsCheck.splice(index, 1)
      this.result.splice(index, 1)
    },
    // 关闭弹窗
    close() {
      this.dialogVisible = false
      document.body.removeChild(this.$el)
    },
    // 选完，点击确定
    choose() {
      if (this.result.length < 1) {
        return this.$message.error('请选择商品')
      }
      if (this.config.count > 0 && this.itemsCheck.length > this.count) {
        return this.$message.error(`最多选择${this.config.count}个商品`)
      }

      this.$emit('choose', this.result)
      this.close()
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-dialog {
  width: 90%;
  max-width: none;
}
</style>
